import React, { useEffect, useState, useRef } from "react";
import axios from "axios";
import { List, Toast } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { List as VirtualizedList, AutoSizer } from "react-virtualized";
import { getCurrentCity } from "../../utils";
// import NavHeader from "../../components/NavHeader";

import "./index.less";
import "react-virtualized/styles.css";

const url = "http://192.168.9.228:9999";

// 标题高度
const TITLE_HEIGHT = 38;
// 城市名称高度
const CITYNAME_HEIGHT = 52;

const formatCityIndex = (data) => {
  switch (data) {
    case "#":
      return "当前定位";
    case "hot":
      return "热门城市";
    default:
      return data.toUpperCase();
  }
};

// 数据格式化
function formatCityData(data) {
  const cityList = {};
  data.forEach((item) => {
    const first = item.pinyin.slice(0, 1);
    if (cityList[first]) {
      cityList[first].push(item);
    } else {
      cityList[first] = [item];
    }
  });
  const cityIndex = Object.keys(cityList).sort();
  return { cityList, cityIndex };
}

// 有房源的城市
const HOUSE_CITY = ["北京", "上海", "广州", "深圳"];

export default function CityList() {
  // 城市列表
  const [cityList, setCityList] = useState({});
  // 字母列表
  const [cityIndex, setCityIndex] = useState([]);
  // 指定右侧字母索引列表是否高亮
  const [activeIndex, setActiveIndex] = useState(0);

  // 创建ref对象
  const listRef = useRef();

  // 编程式导航的hook
  const navigate = useNavigate();

  useEffect(() => {
    getCityList();
  }, []);

  // 获取城市列表
  async function getCityList() {
    try {
      // 城市列表
      const list = await axios.get(url + "/area/city?level=1");
      // 热门城市
      const hot = await axios.get(url + "/area/hot");
      // 获取定位地址
      const curCity = await getCurrentCity();

      const { cityList, cityIndex } = formatCityData(list.data.body);

      cityList["hot"] = hot.data.body;
      cityList["#"] = [curCity];

      cityIndex.unshift("hot");
      cityIndex.unshift("#");

      setCityList((list) => (list = cityList));
      setCityIndex((index) => (index = cityIndex));
    } catch (e) {
      console.log(e);
    }
  }

  // 渲染城市列表
  function renderCityList({ index, key, style }) {
    const letter = cityIndex[index];
    return (
      <div className="city" key={key} style={style}>
        <div className="title">{formatCityIndex(letter)}</div>
        {cityList[letter].map((item) => (
          <div className="name" key={item.value} onClick={() => changeCity(item)}>
            {item.label}
          </div>
        ))}
      </div>
    );
  }

  // 动态计算每一行高度
  function getRowHeight({ index }) {
    const list = cityList[cityIndex[index]];
    return TITLE_HEIGHT + CITYNAME_HEIGHT * list.length;
  }

  // 渲染城市右侧索引
  function renderCityIndex() {
    return cityIndex.map((item, index) => (
      <li className="city-index-item" key={item} onClick={() => listRef.current.scrollToRow(index)}>
        <span className={activeIndex === index ? "index-active" : ""}>
          {item === "hot" ? "热" : item.toUpperCase()}
        </span>
      </li>
    ));
  }

  // 用于获取list组件中渲染行的信息
  function onRowsRendered({ startIndex }) {
    if (activeIndex !== startIndex) {
      setActiveIndex(startIndex);
    }
  }

  function changeCity({ label, value }) {
    if (HOUSE_CITY.includes(label)) {
      localStorage.setItem("HKZF_CITY", JSON.stringify({ label, value }));
      navigate(-1);
    } else {
      return Toast.show({ content: "当前城市没有房源" });
    }
  }

  return (
    <div className="cityList">
      {/* <NavHeader title="城市选择" onBack={() => navigate(-1)} /> */}

      {/* 渲染城市列表 */}
      <List className="cityList-box">
        <AutoSizer>
          {({ width, height }) => (
            <VirtualizedList
              ref={listRef}
              rowCount={cityIndex.length}
              rowRenderer={renderCityList}
              width={width}
              height={height}
              rowHeight={getRowHeight}
              onRowsRendered={onRowsRendered}
              scrollToAlignment="start"
            />
          )}
        </AutoSizer>
      </List>

      {/* 渲染城市右侧索引 */}
      <ul className="city-index">{renderCityIndex()}</ul>
    </div>
  );
}
